# -*- coding: utf-8 -*-

# 将原始DEM数据与水下地形成果合并，生成一个新的DEM文件
import os

import arcpy
from arcpy import env
from arcpy.sa import *

import numpy as np
import random


def merge_dems(arcpy_workspace_path, dem1_path, dem2_path, abs_output_path, mosaic_method="BLEND"):
    """
    Merges two DEM (Digital Elevation Model) raster datasets into a single output raster.

    Args:
        dem1_path (str): Path to the first DEM raster dataset.
        dem2_path (str): Path to the second DEM raster dataset.
        output_path (str): Path where the merged DEM raster dataset will be saved.
        mosaic_method (str, optional): The mosaic method to use for merging the DEMs. Defaults to "BLEND".

    Returns:
        None: The function saves the merged DEM to the specified output path.
    """

    # Set the ArcPy environment
    arcpy.env.workspace = arcpy_workspace_path
    print("arcpy_workspace_path: " + arcpy_workspace_path)
    print("output_path: " + abs_output_path)

    # Check out the Spatial Analyst extension license
    arcpy.CheckOutExtension("Spatial")

    # Ensure the output directory exists
    if not arcpy.Exists(abs_output_path):
        arcpy.env.workspace = os.path.abspath(abs_output_path)

        # Mosaic the DEMs
    # 假设你想要重叠区域的最大值
    # output_dem = Con(IsNull(dem1_path), dem2_path, Con(IsNull(dem2_path), dem1_path, Minimum(dem1_path, dem2_path)))
    # 首先，我们比较两个DEM，找出dem1_path中较小的值
    smaller_dem1 = Con(dem1_path < dem2_path, dem1_path, dem2_path)

    # 然后，我们比较两个DEM，找出dem2_path中较小的值
    smaller_dem2 = Con(dem2_path < dem1_path, dem2_path, dem1_path)

    # 最后，我们比较上面两步得到的结果，以找出两个DEM中真正的最小值
    output_dem = Con(IsNull(dem1_path), dem2_path, Con(IsNull(dem2_path), dem1_path, smaller_dem1))
    output_dem = Con(IsNull(output_dem), dem1_path, Con(IsNull(dem2_path), dem2_path, smaller_dem2))

    # 保存输出
    output_dem.save(abs_output_path)

    # Release the Spatial Analyst extension license
    arcpy.CheckInExtension("Spatial")

# Example usage:
# dem1_path = "path_to_dem1.tif"
# dem2_path = "path_to_dem2.tif"
# output_dem_path = "path_to_output_dem.tif"

# merge_dems(dem1_path, dem2_path, output_dem_path)
